/*
 * @lc app=leetcode.cn id=53 lang=javascript
 *
 * [53] 最大子序和
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number}
 */

// 前缀和数组中当前值减去前面的最小值
var maxSubArray = function (nums) {
  let max = nums[0];
  let min = 0;

  let total = 0;
  for (let i = 0; i < nums.length; i++) {
    total += nums[i];
    max = Math.max(total - min, max);
    min = Math.min(total, min)
  }
  return max;
};

/**
 * 复习 2021-08-04
 */

// 区间和问题用前缀和解决
var maxSubArray = function (nums) {
  let sums = [0];
  for (let i = 0; i < nums.length; i++) sums[i + 1] = sums[i] + nums[i];
  let result = -Infinity, min = Infinity;
  for (let i = 0; i < sums.length; i++) {
    result = Math.max(sums[i] - min, result);
    min = Math.min(sums[i], min)
  }
  return result;
}

// 动态优化求解
var maxSubArray = function (nums) {
  let n = nums.length;
  let f = new Array(n);
  f[0] = nums[0];
  let ans = f[0];
  for (let i = 1; i < n; i++) {
    f[i] = Math.max(f[i - 1] + nums[i], nums[i]);
    ans = Math.max(ans, f[i]);
  }
  return ans;
}
// @lc code=end

